package com.zhouyu.fileSync.FSclient.transmission.communicationBetweenClients.client;

import com.zhouyu.fileSync.FSclient.transmission.communicationBetweenClients.api.CommunicationService;
import com.zhouyu.fileSync.FScommon.commonUtils.FileUtils;
import com.zhouyu.fileSync.FScommon.entities.FileRoute;
import io.netty.util.internal.StringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhouyu74748585@hotmail.com on 2019/9/19
 **/
public class CommunicationSyncJob implements Runnable {
    Logger logger = LogManager.getLogger(CommunicationSyncJob.class);
    private CommunicationClient ct;

    public CommunicationSyncJob(CommunicationClient ct) {
        this.ct = ct;
    }

    @Override
    public void run() {
        CommunicationSyncJobSchedule.JOB_STATUS.put(ct.getCcId(),System.currentTimeMillis());
        try {
            int failedCount=0;
            boolean channelReady=false;
            while (!channelReady) {
                if (ct.getChannel()!=null&& ct.getChannel().isWritable()) {
                    channelReady=true;
                } else {
                    try {
                        if (failedCount<=10) {
                            failedCount++;
                            Thread.sleep(1000);
                        }else {
                            break;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (channelReady) {
                for (FileRoute targetFile : ct.getInitiator().getTargetFiles()) {
                    if (targetFile.isSync()||!CommunicationSyncJobSchedule.ONCE_JOB.containsKey(targetFile)) {
                        getFile(targetFile);
                        if (!targetFile.isSync()) {
                            CommunicationSyncJobSchedule.ONCE_JOB.put(targetFile, System.currentTimeMillis());
                        }
                    }
                }
            }else {
                logger.error("failed to get writable channel");
            }
        }finally {
            CommunicationSyncJobSchedule.JOB_STATUS.remove(ct.getCcId());
        }
    }

    private void getFile(FileRoute fileRoute){
        File currentFile=new File(fileRoute.getTargetFilePath());
        try {
            CommunicationService cs=ct.getCommunicationService();
            String oldMd5=null;
            Long lastModified=null;
            Long oldFileSize=null;
            if (currentFile.exists()){
                oldMd5=FileUtils.getMd5(currentFile);
                lastModified=FileUtils.getFileLastModified(currentFile);
                oldFileSize=FileUtils.getFileSize(currentFile);
            }
            String newMd5= cs.getFileMD5FromTarget(fileRoute.getSourceFilePath(), oldMd5,
                    lastModified, oldFileSize,fileRoute.getUpdateRule(), ct.getTarget(), ct.getInitiator());
            if (!StringUtil.isNullOrEmpty(newMd5)){
                logger.info("get file MD5:"+fileRoute.getSourceFilePath()+":"+newMd5);
                File file=cs.getFileFromTarget(fileRoute.getSourceFilePath(),ct.getTarget());
                logger.info("get file:"+file.getAbsolutePath());
                RandomAccessFile destFile = new RandomAccessFile(file, "rw");
                FileChannel destFileChannel = destFile.getChannel();
                //TODO 设置重试次数,不过这个和文件大小相关,不好设置
                while (true){
                    try {
                        FileLock fl =destFileChannel.tryLock();
                        if (fl.isValid()){
                            break;
                        }
                    }catch (Exception e){
                        System.out.println(false);
                        TimeUnit.SECONDS.sleep(1);
                    }
                }
                String md5= FileUtils.getMd5(file);
                if (md5.equals(newMd5)) {
                    File target = new File(fileRoute.getTargetFilePath());
                    if (target.exists()) {
                        target.delete();
                    }
                    destFileChannel.close();
                    destFile.close();
                    file.renameTo(target);
                    logger.info("move file to :" + fileRoute.getTargetFilePath() + "");
                }else {
                    throw new Exception("md5 check failed");
                }
            }
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
        }
    }
}
